﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RepositoryUtil.SQL
{
    public class SqlUtil<T>
        where T : IConvertible
    {
        public static T GetValue(DataRow drow, string fieldName)
        {
            object value = null;

            if (drow != null && drow.Table.Columns.Contains(fieldName))
            {
                value = CastValue(drow[fieldName]);
            }

            if (value == null || value == DBNull.Value)
            {
                value = default(T);

                if (typeof(T).Name.ToLower() == "string")
                {
                    value = "";
                }
            }

            return (T)value;
        }

        private static T CastValue(object value)
        {
            var type2String = typeof(T).Name.ToLower();

            if (value != null && value != DBNull.Value)
            {
                string valueString = value.ToString();
                switch (type2String)
                {
                    case "string":
                        value = valueString;
                        break;
                    case "int32":
                        int intTmp = 0;
                        int.TryParse(valueString, out intTmp);
                        value = intTmp;
                        break;
                    case "int64":
                        long int64Tmp = 0;
                        Int64.TryParse(valueString, out int64Tmp);
                        value = int64Tmp;
                        break;
                    case "boolean":
                        byte bitValue;
                        if (byte.TryParse(valueString, out bitValue))
                        {
                            value = Convert.ToBoolean(bitValue);
                        }
                        else
                        {
                            value = Convert.ToBoolean(valueString);
                        }
                        break;
                    case "datetime":
                        DateTime dateTmp;
                        DateTime.TryParse(valueString, out dateTmp);
                        value = dateTmp;
                        break;
                    default:
                        break;
                }
            }
            else
            {
                if (type2String == "string")
                    value = "";
                else
                    value = default(T);
            }

            return (T)value;
        }
    }
}
